package com.wfm.niuke;

import org.junit.Test;

/**
 * [岛屿的周长]
 * 主要延用岛屿的个数代码
 * 区别是，dfs需要返回值
 * 返回值的确定：遇到超出边界返回1，遇到海水也是返回1，然后每种遍历相加
 */
public class IslandPerimeter463 {
    public int islandPerimeter(int[][] grid) {
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j]==1){
                    return dfs(grid,i,j);
                }
            }
        }
        return 0;
    }
    int dfs(int[][] grid,int i ,int j){
        if(!inArea(grid, i , j)){
            return 1;
        }
        if(grid[i][j]==0){
            return 1;
        }
        if(grid[i][j]==2){
            return 0;
        }
        grid[i][j]=2;
        return dfs(grid,i-1,j)+
        dfs(grid,i+1,j)+
        dfs(grid,i,j-1)+
        dfs(grid,i,j+1);
    }

    private boolean inArea(int[][] grid, int i, int j) {
        if(i<0||i>=grid.length||j<0||j>=grid[0].length) return false;
        else return true;
    }

    @Test
    public void test200(){
        System.out.println(islandPerimeter(new int[][]{
                {0,1,0,0},
                {1,1,1,0},
                {0,1,0,0},
                {1,1,0,0}
        }));
    }
}
